<?php
// +----------------------------------------------------------------------
// | Qbt CMS Plugin
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2018 http://www.qbt8.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 黄老邪 <develop02@qbt8.com>
// +----------------------------------------------------------------------
namespace plugins\qbt_wx_os\controller;
use think\Controller;
use plugins\qbt_wx_os\model\WxOsConfigModel;
use plugins\qbt_wx_os\model\WxOsReplyModel;
use plugins\qbt_wx_os\model\WxOsMenuModel;
use think\Db;


class WxReplyController extends Controller
{
    public function _initialize()
    {
        $this->data = $this->request->param();
        $this->wocmodel = new WxOsConfigModel();
        $this->wormodel = new WxOsReplyModel();
        $this->wommodel = new WxOsMenuModel();
    }

    public function valid()
    {

        if(isset($_GET["echostr"])){
            $echoStr = $_GET["echostr"];
            if ($this->checkSignature()) {
                echo $echoStr;
                exit;
            }
        }else{
            $this->responseMsg();
        }

    }


    public function checkSignature()
    {
        

        //$info = $this->wocmodel->data_list();
        $lists = Db::name('plugin')->where(['name'=>'QbtWxOs'])->find();
        $fosn = $lists['config'];
        $info = json_decode($fosn,true);

        $token = $info['token'];
        $data = $this->data;

        //$data = $this->request->param();

        $signature = $data["signature"];
        $timestamp = $data["timestamp"];
        $nonce = $data["nonce"];
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }


    public function responseMsg(){

        $postr = file_get_contents("php://input");
        if(!empty($postr)){
            $dataObj = simplexml_load_string($postr);
            $this->check_type($dataObj);
        }else{
            echo '';die;
        }
    }

    // public function check_type($dataObj){
    //     if( strtolower( $dataObj->MsgType ) == 'event') {
    //         if( strtolower( $dataObj->Event ) == 'subscribe' ){
    //             $toUser=$dataObj->FromUserName;
    //             $fromUser=$dataObj->ToUserName;
    //             $time=time();
    //             $msgType = 'text';
    //             $info = $this->wormodel->data_info('type = 9');
    //             $content = $info['str'];
    //             $template = "<xml>
       //              <ToUserName><![CDATA[%s]]></ToUserName>
       //              <FromUserName><![CDATA[%s]]></FromUserName>
       //              <CreateTime>%s</CreateTime>
       //              <MsgType><![CDATA[%s]]></MsgType>
       //              <Content><![CDATA[%s]]></Content></xml>";
    //             echo sprintf($template,$toUser,$fromUser,$time,$msgType,$content);

    //         }
    //     }
    // }
     public function check_type($dataObj){
        $toUser=$dataObj->FromUserName;
        $fromUser=$dataObj->ToUserName;
        $time=time();
        $data['touser'] = $toUser;
        $data['fromuser'] = $fromUser;
        $data['time'] = $time;
        if( strtolower( $dataObj->MsgType ) == 'event') {
            $arr1 = array();
            if( strtolower( $dataObj->Event ) == 'subscribe' ){
                $info = $this->wormodel->data_info('type = 9');
                $data['content'] = $info['str'];
                $data['type'] = 1;
                $data['msgtype'] = 'text';
                $this->echo_sprintf($data);
            }else if(strtolower( $dataObj->Event ) == 'click'){
                $key = strtolower( $dataObj->EventKey );
                $where['key'] = ['like',"%$key%"];
                $info = $this->wommodel->data_info($where);
                if($info['name_type'] == 1){
                    if($info['type'] == 1){
                        $data['type'] = 1;
                        $data['content'] = $info['content'];
                        $data['msgtype'] = 'text';
                    }else if($info['type'] == 2){
                        $data['type'] = 2;
                        $arr2 = json_decode($info['content'],true);
                        $data['msgtype'] = 'image';
                        $data['content'] = $arr2['media_id'];
                    }else if($info['type'] == 3){
                        $data['type'] = 3;
                        $arr2 = json_decode($info['content'],true);
                        $data['msgtype'] = 'news';
                        $data['title'] = $arr2['title'];
                        $data['description'] = $arr2['desc'];
                        $data['picUrl'] = cmf_get_image_url($arr2['img_url1']);
                        $data['url'] = $arr2['tz_url'];
                    }
                    $this->echo_sprintf($data);
                }
            }

           
        }else if(strtolower($dataObj->MsgType ) == 'text'){
            if(!empty(trim($dataObj->Content))){
                $keyword = $dataObj->Content;
                $where['keyword'] = array('like',"%$keyword%");
                $where['status'] = 1;
                $info  = $this->wormodel->data_info($where);
                if(empty($info)){
                    $data['type'] = 1;
                    $data['msgtype'] = 'text';
                    $data['content'] = '对不起！没有相关的内容！';
                }else{
                    if($info['type'] == 1){
                        $data['type'] = 1;
                        $data['msgtype'] = 'text';
                        $data['content'] = $info['str'];

                    }else if($info['type'] == 2){
                        $data['type'] = 2;
                        $data['content'] = $info['media_id'];
                        $data['msgtype'] = 'image';

                    }else if($info['type'] == 3){
                        $arr = array();
                        $arr = json_decode($info['img_str'],true);
                        $data['msgtype'] = 'news';
                        $data['title'] = $arr['title'];
                        $data['description'] = $arr['desc'];
                        $data['picUrl'] = cmf_get_image_url($arr['img_url1']);
                        $data['url'] = $arr['url'];
                        $data['type'] = 3;

                    }
                }

                $this->echo_sprintf($data);
            }
        }
    }

    //输出归纳
    public function echo_sprintf($data){
        if($data['type'] == 1){
            $template = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content></xml>";
            echo sprintf($template,$data['touser'],$data['fromuser'],$data['time'],$data['msgtype'],$data['content']);
        }else if($data['type'] == 2){
            $template = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Image><MediaId><![CDATA[%s]]></MediaId></Image></xml>";
            echo sprintf($template,$data['touser'],$data['fromuser'],$data['time'],$data['msgtype'],$data['content']);
        }else if($data['type'] == 3){
            $str = " <item>
                                <Title><![CDATA[".$data['title']."]]></Title>
                                <Description><![CDATA[".$data['description']."]]></Description>
                                <PicUrl><![CDATA[".$data['picUrl']."]]></PicUrl>
                                <Url><![CDATA[".$data['url']."]]></Url>
                            </item>";
            echo "<xml>
                        <ToUserName><![CDATA[".$data['touser']."]]></ToUserName>
                        <FromUserName><![CDATA[".$data['fromuser']."]]></FromUserName>
                        <CreateTime>".$data['time']."</CreateTime>
                        <MsgType><![CDATA[".$data['msgtype']."]]></MsgType>
                        <ArticleCount>1</ArticleCount>
                        <Articles>
                           ".$str."
                        </Articles>
                    </xml>";
        }
    }
}